package campus.aiit.ssl.util;

import java.sql.*;

public class RoleUtil {

  public static boolean isAdmin(String userId) throws Throwable {
    // use JDBC...
    Class.forName("org.mariadb.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ess", "root", "root");
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select role_id from user where id = '" + userId + "'");
    resultSet.next();
    byte roleId = resultSet.getByte("role_id");
    resultSet.close();
    statement.close();
    connection.close();
    return roleId == 0;
  }

  public static String currentUserIdOfDao() throws Throwable {
    // 三重检查：拿到此次请求的session > 获取该用户的工号 > 是否返回该工号
    String userId = ContextUtil.userId();
    if (userId == null) return null;
    return isAdmin(userId) ? null : userId;
  }
  public static String userIdOfDao(String userId) throws Throwable {
    return isAdmin(userId) ? null : userId;
  }
}